package com.ztewatch.wearcontacts;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.ztewatch.wearcontacts.utils.CallUtil;
import com.ztewatch.wearcontacts.utils.ContactQuery;

public class WearContactDisplayActivity extends Activity implements
		OnClickListener {
	public static final String CONTACT_DETAIL_FALG = "contact_detail_flag";
	private TextView name_tv;
	private TextView number_tv;
	private ImageView photo;
	private ImageView call_phone_btn;
	private ImageView send_msg_btn;
	private ImageView edit_contact_btn;
	private Uri mLookupUri = null;
	private boolean isContactReady = false;
	int starred_id = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_display);
		initView();
		mLookupUri = getIntent().getData();
		isContactReady = getIntent().getBooleanExtra(
				WearContactGroupDetailActivity.CONTACT_READY_FLAG, false);
		if (isContactReady) {
			edit_contact_btn.setEnabled(false);
		}
	}

	private void initView() {
		name_tv = (TextView) findViewById(R.id.contact_display_name);
		number_tv = (TextView) findViewById(R.id.contact_display_number);
		photo = (ImageView) findViewById(R.id.contact_dispaly_photo);
		call_phone_btn = (ImageView) findViewById(R.id.contact_detail_call_btn);
		send_msg_btn = (ImageView) findViewById(R.id.contact_detail_sendmsg_btn);
		edit_contact_btn = (ImageView) findViewById(R.id.contact_detail_edit_btn);
		call_phone_btn.setOnClickListener(this);
		send_msg_btn.setOnClickListener(this);
		edit_contact_btn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.contact_detail_call_btn:
			String number = number_tv.getText().toString();
			Intent intent1 = CallUtil.getCallIntent(number);
			startActivity(intent1);
			break;
		case R.id.contact_detail_sendmsg_btn:
			String number2 = number_tv.getText().toString();
			Intent intent2 = new Intent();
			intent2 = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto",
					number2, null));
			startActivity(intent2);
			break;
		case R.id.contact_detail_edit_btn:
			Intent intent = new Intent();
			intent.setAction(PasswordkeypadActivity.EDIT_CONTACT_ACTION);
			intent.setData(mLookupUri);
//			if (getResources().getBoolean(R.bool.config_LGU_flag) && starred_id == 0) {
				intent.setClass(WearContactDisplayActivity.this,
						WearContactEditActivity.class);
//			} else {
//				intent.putExtra(CONTACT_DETAIL_FALG, true);
//				intent.setClass(WearContactDisplayActivity.this,
//						PasswordkeypadActivity.class);
//			}
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	// private void showDelDialog() {
	// new AlertDialog.Builder(this)
	// .setMessage(
	// getResources().getString(
	// R.string.display_contact_del_msg))
	// .setPositiveButton(
	// getResources().getString(
	// R.string.display_contact_del_ok),
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// new Thread(new Runnable() {
	//
	// @Override
	// public void run() {
	// if (delContact()) {
	// finish();
	// }
	// }
	// }).start();
	//
	// }
	// })
	// .setNegativeButton(
	// getResources().getString(R.string.edit_contact_cancel),
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	//
	// }
	// }).create().show();
	// }

	// private boolean delContact() {
	// String displayname = name_tv.getText().toString();
	// Cursor c = getContentResolver().query(Data.CONTENT_URI,
	// new String[] { Data.RAW_CONTACT_ID },
	// Contacts.DISPLAY_NAME + "=?", new String[] { displayname },
	// null);
	//
	// ArrayList<ContentProviderOperation> ops = new
	// ArrayList<ContentProviderOperation>();
	// if (c.moveToFirst()) {
	// do {
	// long id = c.getLong(c.getColumnIndex(Data.RAW_CONTACT_ID));
	// // ops.add(ContentProviderOperation.newDelete(
	// // ContentUris.withAppendedId(RawContacts.CONTENT_URI,
	// // id)).build());
	// ops.add(ContentProviderOperation
	// .newDelete(RawContacts.CONTENT_URI)
	// .withSelection(RawContacts._ID + "=?",
	// new String[] { String.valueOf(id) }).build());
	// try {
	// getContentResolver().applyBatch(ContactsContract.AUTHORITY,
	// ops);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// } while (c.moveToNext());
	// c.close();
	// return true;
	// }
	// return false;
	// }

	@Override
	protected void onStart() {
		super.onStart();
		getLoaderManager().initLoader(0, null, loaderCallbacks);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(0);
	}

	private void setDataToView(Cursor cursor) {
		String number_type = cursor.getString(ContactQuery.DATA2);

		if (number_type != null
				&& number_type.equals(String.valueOf(Phone.TYPE_MOBILE))) {
			String number = cursor.getString(ContactQuery.DATA1);
			number_tv.setText(number);
		}
		String display_name = cursor.getString(ContactQuery.DISPLAY_NAME);
		name_tv.setText(display_name);
		byte[] str = cursor.getBlob(ContactQuery.DATA15);

		if (str != null) {
			InputStream inputStream = new ByteArrayInputStream(str);
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			photo.setImageBitmap(bitmap);
		} else {
			photo.setImageResource(R.drawable.ic_address_portrait);
		}
		
		int starred_index = cursor
				.getColumnIndex(Contacts.STARRED);
		if (starred_index != -1) {
			starred_id = cursor.getInt(starred_index);
		}
	}

	private final LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
			if (cursor != null) {
				if (!cursor.moveToFirst()) {
					cursor.close();
				} else {
					do {
						setDataToView(cursor);
					} while (cursor.moveToNext());
				}
			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			if (mLookupUri != null) {
				Uri uri = Uri.withAppendedPath(mLookupUri,
						Contacts.Entity.CONTENT_DIRECTORY);
				return new CursorLoader(WearContactDisplayActivity.this, uri,
						ContactQuery.COLUMNS, null, null,
						Contacts.Entity.RAW_CONTACT_ID);
			} else {
				return null;
			}

		}
	};
}
